package cz.data.common.support.db.manage;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cz.data.common.exception.DataException;
import cz.data.common.support.db.core.DbColumn;
import cz.data.common.support.db.core.DbTable;

import java.util.List;
import java.util.Objects;
import java.util.Properties;

public interface DbManage extends Cloneable {

    List<DbTable> getTables(String dbName, String schemaName);

    List<DbColumn> getTableColumns(String dbName, String schemaName, String tableName);

    boolean createTable(DbTable table, Properties properties);

    boolean deleteTable(DbTable table);

    boolean insertData(DbTable table, JSONObject record);

    boolean updateData(DbTable table, JSONObject record);

    boolean removeData(DbTable table, JSONObject record);

    IPage<JSONObject> getPageData(DbTable table, List<String> fields, List<Condition> conditions, Page<JSONObject> page);

    JSONObject getDataById(DbTable table, JSONObject params);

    default void close() throws Exception {

    }

    static JSONObject filterJson(List<DbColumn> columns, JSONObject record) {
        JSONObject payload = new JSONObject();
        for (DbColumn column : columns) {
            String colName = column.getColName();
            Object value = record.get(colName);
            if (Objects.nonNull(value)) {
                payload.put(colName, value);
            } else if (Boolean.TRUE.equals(column.getColKey())) {
                throw new DataException("缺少必须的主键参数");
            }
        }
        return payload;
    }
}
